package com.nes.fiber.service;

import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.SuspendExecution;
import co.paralleluniverse.strands.SuspendableRunnable;
import co.paralleluniverse.strands.channels.Channel;
import co.paralleluniverse.strands.channels.Channels;
import org.springframework.stereotype.Service;


/**
 * Created by wdq on 17-4-6.
 */
@Service
public class FiberServiceImpl implements FiberService {

    @Override
    public Integer getNumberCount(Integer num) throws InterruptedException, SuspendExecution {

        Channel<Integer> channel = Channels.newChannel(1);
        Fiber<Integer> fiber1 = new Fiber<Integer>((SuspendableRunnable) () ->  {
                Integer sum = 0;
                for (int i = 1; i <= num; i++) {
                    Fiber.sleep(100);
                    sum += i;
                }
                channel.send(sum);
                channel.close();
        }).inheritThreadLocals().start();
//
//        Fiber fiber2 = new Fiber<Integer>(){
//            @Override
//            protected Integer run() throws SuspendExecution, InterruptedException {
//                return  channel.receive();
//            }
//         }.inheritThreadLocals().start();

        Integer integer = channel.receive();
        return integer;
    }

}
